import { AvatarDropdown, AvatarName, Footer, Question } from '@/components';
import { PROJECT_NAME } from '@/constants';
import { getLoginUserUsingGet } from '@/services/backend/userController';
import { SettingDrawer } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from '@umijs/max';
import { history } from '@umijs/max';
import {Button, message, Typography} from 'antd';
import adminSettings from '../config/adminSettings';
import defaultSettings from '../config/defaultSettings';
import { requestConfig } from './requestConfig';

const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';

const WHIET_LIST = [loginPath, '/user/register'];

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<InitalState> {
  const initialState: InitalState = {
    currentUser: undefined,
    settings: defaultSettings,
  };

  // 如果不是登录页面，执行
  const { location } = history;
  // if (!location.pathname.startsWith(loginPath)) {
  if (!WHIET_LIST.includes(location.pathname)) {
    //获取当前的登录用户
    try {
      const res = await getLoginUserUsingGet();
      initialState.currentUser = res.data;
      //若为管理员,则修改为管理员的布局
      if (res.data?.role === 'admin') {
        initialState.settings = adminSettings;
      }
    } catch (error: any) {
      message.error('获取用户失败,' + error.message);
    }
  }

  return initialState;
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
// @ts-ignore
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  const { currentUser } = initialState || {};
  const isAdmin = currentUser?.role === 'admin';

  return {
    actionsRender: () => [<Question key="doc" />],
    avatarProps: {
      src: initialState?.currentUser?.avatar,
      title: <AvatarName />,
      render: (_, avatarChildren) => {
        return <AvatarDropdown menu={true}>{avatarChildren}</AvatarDropdown>;
      },
    },
    waterMarkProps: {
      content: PROJECT_NAME,
    },
    footerRender: () => <Footer />,
    menuHeaderRender: undefined,
    contentStyle: { padding: '0px' },
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        <>
          {children}
          {isDev && (
            <SettingDrawer
              disableUrlParams
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                setInitialState((preInitialState) => ({
                  ...preInitialState,
                  settings,
                }));
              }}
            />
          )}
        </>
      );
    },
    ...(isAdmin ? adminSettings : initialState?.settings),
  };
};

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request = requestConfig;
